<template>
  <div class="stores_list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item"><span class="search-label">输入搜索：</span><Input placeholder="商品名称/条码/编码"
                 v-model='searchObj.keyword'></Input></Col>
          <Col style="display: flex; align-items: center;"
               class="search-item">
          <span class="search-label">商品分类：</span>
          <!-- <Select v-model="searchObj.classify" style="width:200px" @on-change="seleted">
              <OptionGroup :label="ele.categoryName" v-for="(ele, idx) in classifyList" :key='idx'>
                <Option v-for="item in ele.subCategoryList" :value="item.categoryId" :key="item.categoryId">{{ item.categoryName }}</Option>
              </OptionGroup>
            </Select> -->
          <vueTreeselectChoice :width="200"
                               v-model="searchObj.categoryId"
                               :disable-branch-nodes="true"
                               @input="seleted"
                               :options="classifyList"
                               permissionCode='1'></vueTreeselectChoice>
          </Col>
          <Col class="search-item">
          <span class="search-label">状态：</span>
          <Select v-model="searchObj.goodsStatus"
                  @on-change="seleted"
                  style="width:180px"
                  placeholder='请选择'>
            <Option v-for="item in typeList"
                    :value="item.typeCode"
                    :key="item.typeCode">{{ item.typeName }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">供应商：</span>
          <Select v-model="searchObj.supplierId"
                  @on-change="seleted"
                  filterable
                  style="width:180px"
                  placeholder='请选择'>
            <Option v-for="item in supplierNopage"
                    :value="item.id"
                    :key="item.id">{{ item.suppName }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="seleted">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item"><Button class="search-btn"
                  type="primary"
                  style="margin-right:8px"
                  v-if="hasPermission(['moms:product:productcreate'])"
                  @click="skipAdd">新增商品</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe
           class="table-list"
           :columns="columns"
           :data="tableData"
           @on-sort-change="sortTable"
           :loading="loading"
           :height="tableHeight">
      <template slot-scope="{ row }"
                slot="thumbnail">
        <div><img :src="row.thumbnail?row.thumbnail:defaultUrl"
               style="width: 90px;height: 60px;display: block;margin: 15px 0;"></div>
      </template>
      <template slot-scope="{ row }"
                slot="classify">
        <div>{{row.parentCategoryName+' - '+row.categoryName}}</div>
      </template>
      <template slot-scope="{ row }"
                slot="goodsStatus">
        <span>{{['','正常','冻结'][row.goodsStatus]}}</span>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <i class="iconsys icondetail"
           title="查看"
           v-if="hasPermission('moms:scs:productdetail')"
           @click='skipDetail(row)'></i>
        <i class="iconsys iconedit"
           title="编辑"
           v-if="hasPermission('moms:scs:productupdate')"
           @click='skipEdit(row)'></i>
        <i class="iconsys icondongjie"
           title="冻结商品"
           v-if="hasPermission('moms:scs:productfroze')"
           @click='freeze(row)'></i>
        <!-- <Poptip confirm
                title="确认复制该商品信息吗？"
                transfer
                v-if="hasPermission(['moms:product:productcopy'])"
                style="text-align:left"> -->
        <i class="iconsys iconfuzhi"
           title="复制商品"
           v-if="hasPermission('moms:scs:productcopy')"
           @click="sureCover(row)"></i>
        <!-- </Poptip> -->
      </template>
    </Table>
    <Row type='flex'
         justify="end"
         style='padding: 20px'>
      <Col>
      <Page :total="pageObj.total"
            :page-size='pageObj.pageSize'
            :current='pageObj.pageIndex'
            :page-size-opts='[10,20,50,100]'
            show-total
            show-sizer
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <Modal v-model="modalShow"
           width="480"
           title="冻结商品"
           :closable='false'>
      <div style="padding: 0 15px">当商品存在有效库存时，无法进行冻结操作；商品冻结确认冻结后，商品信息将停止使用</div>
      <div slot="footer">
        <Button style="width:78px;margin-right:10px"
                @click='cancel'>考虑一下</Button>
        <Button type="primary"
                style="width:78px"
                @click='sureFreeze'>确认冻结</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
// import { shopCategoryList } from '@/api/goods/index'
import { inventoryCategoryList, supplierNopage, inventoryGoodsList, inventoryGoodsFreeze, getOrgTagList } from '@/api/purchase/index'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import { mapState } from 'vuex'
export default {
  name: 'stores_list',
  components: { vueTreeselectChoice },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName,
      orgId: state => state.user.orgId
    }),
    tableHeight () {
      let height = this.tableData.length > 6 ? 580 : 0
      return height
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'stores_list') {
        this.getGoodsList()
      }
    }
  },
  data () {
    return {
      tableData: [],
      loading: false,
      supplierNopage: [],
      orgTagId: '',
      orgTagName: '',
      orgTag: {},
      modalShow: false,
      skuId: '',
      searchObj: {
        keyword: '',
        goodsStatus: 0,
        categoryId: null,
        supplierId: ''
      },
      defaultUrl: require('@/assets/images/default.png'),
      typeList: [
        { typeCode: 0, typeName: '全部' },
        { typeCode: 1, typeName: '正常' },
        { typeCode: 2, typeName: '冻结' }
      ],
      classifyListArr: [],
      classifyList: [],
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      sortBy: 'asc',
      columns: [
        {
          title: '商品编码',
          key: 'skuId',
          width: 120,
          sortable: 'custom',
          sortType: 'asc'
        },
        {
          title: '商品主图',
          slot: 'thumbnail'
        },
        {
          title: '商品名称',
          key: 'skuName'
        },
        {
          title: '条码',
          key: 'barcode'
        },
        {
          title: '商品分类',
          slot: 'classify'
        },
        {
          title: '供应商名称',
          key: 'supplierName'
        },
        {
          title: '采购单价',
          key: 'standardPrice'
        },
        {
          title: '状态',
          slot: 'goodsStatus'
        }
      ]
    }
  },
  created () {
    if (this.hasPermission(['moms:scs:productdetail', 'moms:scs:productupdate', 'moms:scs:productfroze', 'moms:scs:productcopy'])) {
      this.columns.push({
        title: '操作',
        width: 300,
        slot: 'action'
      })
    }
  },
  mounted () {
    this.getCate()
    this.getTag()
  },
  methods: {
    getCate () {
      inventoryCategoryList({
        merchantId: this.merchantId,
        level: 1,
        offset: 0,
        limit: 10000,
        isShow: 1
      }).then(res => {
        if (res.data.status === 200) {
          this.classifyListArr = (res.data.data.categories || []).map(item => {
            return {
              id: item.sysCategoryId,
              orgName: item.categoryName,
              parentId: item.parentId,
              childList: []
            }
          })
          this.classifyListArr.forEach(ele => {
            inventoryCategoryList({
              merchantId: this.merchantId,
              parentId: ele.id,
              level: 2,
              offset: 0,
              limit: 10000,
              isShow: 1
            }).then(resd => {
              if (resd.data.status === 200) {
                ele.childList = (resd.data.data.categories || []).map(item => {
                  return {
                    id: item.sysCategoryId,
                    orgName: item.categoryName
                  }
                })
              }
            })
          })
          this.classifyList = this.classifyListArr
        }
      })
    },
    skipDetail (row) {
      this.$router.push({ name: 'stores_detail', query: { id: row.skuId } })
    },
    skipEdit (row) {
      this.$router.push({ name: 'stores_edit', query: { id: row.skuId, type: 0 } })
    },
    sureCover (row) {
      this.$router.push({ name: 'stores_edit', query: { id: row.skuId, type: 1 } })
    },
    getGoodsList () {
      this.loading = true
      inventoryGoodsList({
        ...this.searchObj,
        merchantId: this.merchantId,
        categoryId: this.searchObj.categoryId || '',
        goodsStatus: this.searchObj.goodsStatus ? this.searchObj.goodsStatus : '',
        sortBy: this.sortBy,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        if (res.data.status === 200) {
          this.tableData = res.data.data.goods || []
          this.pageObj.total = res.data.data.total
        } else {
          this.$Message.error(`${res.data.message}`)
        }
      })
    },
    getTag () {
      this.orgTagId = []
      getOrgTagList({
        merchantId: this.merchantId,
        id: this.orgId
      }).then(res => {
        console.log(res)
        if (res.data.status === 200) {
          this.orgTag = res.data.data || []
          this.orgTag.forEach(ele => {
            this.orgTagId.push(ele.id)
          })
          this.getSuppeer()
          this.getGoodsList()
        } else {
          his.$Message.error(`${res.data.message}`)
        }
      })
    },
    cancel () {
      this.modalShow = false
    },
    sureFreeze () {
      this.modalShow = false
      inventoryGoodsFreeze({
        merchantId: this.merchantId,
        updater: this.userId,
        updaterName: this.userName,
        skuId: this.skuId
      }).then(res => {
        if (res.data.status === 200) {
          this.getGoodsList()
        } else {
          this.$Message.error(`${res.data.message}`)
        }
      })
    },
    getSuppeer () {
      supplierNopage({
        merchantId: this.merchantId,
        orgTagId: this.orgTagId,
        dispFlag: 1,
        displayOrder: 1,
        supplierTypeCode: 1
      }).then(res => {
        const result = res.data || {}
        if (res.data.status === 200) {
          this.supplierNopage = result.data || []
        } else {
          this.$Message.error(`${result.message}`)
        }
      })
    },
    seleted () {
      this.pageObj.pageIndex = 1
      this.getGoodsList()
    },
    skipAdd () {
      this.$router.push({ name: 'stores_create' })
    },
    reset () {
      this.searchObj = {
        keyword: '',
        goodsStatus: 0,
        categoryId: null,
        supplierId: ''
      }
      this.pageObj = {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      }
      this.getGoodsList()
    },
    freeze (row) {
      this.skuId = row.skuId
      this.modalShow = true
    },
    sortTable (column) {
      this.sortBy = column.order
      this.pageObj.pageIndex = 1
      this.getGoodsList()
    },
    changePageIndex (pageIndex) {
      this.pageObj.pageIndex = pageIndex
      this.getGoodsList()
    },
    changePageSize (pageSize) {
      this.pageObj.pageSize = pageSize
      this.getGoodsList()
    }
  }
}
</script>
